package znzz.quartz.service;

import org.quartz.*;

import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import znzz.quartz.vo.PageTrigger;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by wangjwm on 2017/7/25.
 */
@Repository("jobservice")
public class JobService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 获得所有的Job
     *
     * @return
     */
    public List<JobDetail> getJobs() {
        List<JobDetail> jobDetails = new ArrayList<JobDetail>();
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        try {
            Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
            for(JobKey jobKey : jobKeys) {
                jobDetails.add(scheduler.getJobDetail(jobKey));
            }
            return jobDetails;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得所有的触发器
     *
     * @return
     */
    public List<PageTrigger> getTriggersInfo() {
        List<PageTrigger> triggers = new ArrayList<PageTrigger>();
        GroupMatcher<TriggerKey> matcher = GroupMatcher.anyTriggerGroup();
        try {
            Set<TriggerKey> keys = scheduler.getTriggerKeys(matcher);
            for(TriggerKey key : keys) {
                Trigger trigger = scheduler.getTrigger(key);
                PageTrigger pageTrigger = new PageTrigger();
                pageTrigger.setName(trigger.getJobKey().getName());
                pageTrigger.setGroup(trigger.getJobKey().getGroup());
                pageTrigger.setStatus(scheduler.getTriggerState(key) + "");
                // SimpleTrigger Quartz中最简单Trigger
                // 它是为那种需要在特定的日期/时间启动，且以一个可能的间隔时间重复执行n次的Job所设计的
                if(trigger instanceof SimpleTrigger) {
                    SimpleTrigger simple = (SimpleTrigger) trigger;
                    pageTrigger.setExpression("重复次数:" +
                            (simple.getRepeatCount() == -1 ? "无限" : simple.getRepeatCount()) +
                            ",重复间隔:" + (simple.getRepeatInterval()/1000L));
                    pageTrigger.setDesc(simple.getDescription());
                }
                // CronTrigger不仅可以设定简单的触发时间表，更可以设定非常复杂的触发时间表
                // CronTrigger是基于Unix类似于cron表达式
                if(trigger instanceof CronTrigger) {
                    CronTrigger cron = (CronTrigger) trigger;
                    pageTrigger.setExpression(cron.getCronExpression());
                    pageTrigger.setDesc(cron.getDescription());
                }
                triggers.add(pageTrigger);
            }
            return triggers;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 暂定任务
     *
     * @param name 任务名称
     * @param group 任务分组
     */
    public void stopJob(String name, String group) {
        JobKey key = new JobKey(name, group);
        try {
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 恢复任务
     *
     * @param name 任务名称
     * @param group 任务分组
     */
    public void restartJob(String name, String group) {
        JobKey key = new JobKey(name, group);
        try {
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 立马执行一次任务
     *
     * @param name 任务名称
     * @param group 任务分组
     */
    public void startNowJob(String name, String group) {
        // 将名称为name的Job放入group组中
        JobKey key = new JobKey(name, group);
        try {
            JobDetail job = JobBuilder.newJob(
                    scheduler.getJobDetail(key).getJobClass())
                    .storeDurably()
                    .build();
            scheduler.addJob(job, false);
            scheduler.triggerJob(job.getKey());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除任务
     *
     * @param name 任务名称
     * @param group 任务分组
     */
    public void delJob(String name, String group) {
        JobKey key = new JobKey(name, group);
        try {
            scheduler.deleteJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改触发器时间
     *
     * @param name 任务名称
     * @param group 任务分组
     * @param cron
     */
    public void modifyTrigger(String name, String group, String cron) {
        TriggerKey key = TriggerKey.triggerKey(name, group);
        try {
            Trigger trigger = scheduler.getTrigger(key);
            CronTrigger newTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(key)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();
            scheduler.rescheduleJob(key, newTrigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 暂停调度器
     */
    public void stopScheduler() {
        try {
            if (!scheduler.isInStandbyMode()) {
                scheduler.standby();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}
